package db

import (
	log "github.com/sirupsen/logrus"
	"src/db/db_modle"
	"src/error_msg"
	"src/tools"
)

// 历史最大逾期天数
func DaysOfOverdue(uid uint, logId string) (int, error) {
	orm := GetMysqlOrm()
	defer orm.Close()
	// pay表中uid和review_type,获取借到钱的人订单id
	var orderIds []db_modle.Pay
	var max int64
	// review_type=1 已贷款
	r := orm.Where("user_id = ?", uid).Where("review_type = ?", 1).Find(&orderIds)
	if e := r.Error; e != nil {
		log.Error(e.Error(), logId)
		return 0, e
	}
	// repayment中订单id获取对应的also_time, 与越南当地时间比对
	repayment := db_modle.Repayment{}
	for _, v := range orderIds {
		// 无论是否结清，都计算
		//s := orm.Where("order_id = ?", v.OrderId).Where("repayment_status != ?", 3).First(&repayment)
		s := orm.Where("order_id = ?", v.OrderId).First(&repayment)
		if e := s.Error; e != nil {
			// 未查询到，不能影响其他订单的查询
			log.Error(e.Error(), logId)
			continue
		}

		// 逾期
		if tools.GetVietnamTime().Unix()-repayment.AlsoTime.Unix() > max {
			max = tools.GetVietnamTime().Unix() - repayment.AlsoTime.Unix()
			log.Debugf("历史逾期天数 %+v \n", int(max/(60*60*24)))
		}
	}
	return int(max / (60 * 60 * 24)), nil
}

// 最近一笔结清交易逾期天数
func OverdueDaysOfLastFinishedOrder(uid uint, logId string) (int, error) {
	orm := GetMysqlOrm()
	defer orm.Close()
	// pay表中uid和review_type,获取借到钱的人订单id
	var orderIds db_modle.Pay
	// review_type=1 已贷款
	r := orm.Where("user_id = ?", uid).Where("review_type = ?", 1).Order("id desc").First(&orderIds)
	if e := r.Error; e != nil {
		ne := error_msg.LoanOrderNotFoundError
		log.Error(ne.Error(), logId)
		return 0, ne
	}
	// repayment中订单id获取对应的also_time, 与越南当地时间比对
	// repayment_status=3已结清订单
	repayment := db_modle.Repayment{}
	s := orm.Where("order_id = ?", orderIds.OrderId).Where("repayment_status = ?", 3).First(&repayment)
	if e := s.Error; e != nil {
		ne := error_msg.OverdueOrderNotFoundError
		log.Error(ne.Error(), logId)
		return 0, ne
	}

	// 逾期
	if tools.GetVietnamTime().Unix() > repayment.AlsoTime.Unix() {
		second := tools.GetVietnamTime().Unix() - repayment.AlsoTime.Unix()
		log.Info("最近一笔订单逾期天数 %+v \n", int(second/(60*60*24)), logId)
		return int(second / (60 * 60 * 24)), nil
	}
	return 0, nil
}
